<template>

  <div>Gie仓库：https://gitee.com/emotional-transformation/vue.git</div>
  <div class="todo-container">
    <h1>TodoList</h1>
    <div class="todo-wrap">
      <Header :addTodo="addTodo" />
      <List :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo" />
      <Footer
        :todos="todos"
        :checkAll="checkAll"
        :clearAllCompletedTodos="clearAllCompletedTodos"
      />
    </div>
    
    
  </div>

  
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue"
// 引入直接的子级组件
import Header from "@/components/todoList/Header.vue"
import List from "@/components/todoList/List.vue"
import Footer from "@/components/todoList/Footer.vue"

// 引入接口
import { type Todo } from "@/components/todoList/todo"

// 数据持久化
import { saveTodos, readTodos } from "@/components/todoList/localStorageUtils"

export default defineComponent({
  name: "App",
  // 注册组件
  components: {
    Header,
    List,
    Footer,
  },

  setup() {

    console.log("Demo11 setup")
    // console.log(state)

    const state = reactive<{ todos: Todo[] }>({
      todos: [],
    })
    // 界面加载完毕后过了一会再读取数据
    onMounted(() => {
      setTimeout(() => {
        state.todos = readTodos()
      }, 1000)
    })

    // 添加数据的方法
    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo)
    }
    // 删除数据的方法
    const deleteTodo = (index: number) => {
      state.todos.splice(index, 1)
    }
    // 修改todo的isCompleted属性的状态
    const updateTodo = (todo: Todo, isCompleted: boolean) => {
      todo.isCompleted = isCompleted
    }

    // 全选或者是全不选的方法
    const checkAll = (isCompleted: boolean) => {
      state.todos.forEach(todo => {
        todo.isCompleted = isCompleted
      })
    }

    // 清理所有选中的数据
    const clearAllCompletedTodos = () => {
      state.todos = state.todos.filter(todo => !todo.isCompleted)
    }

    watch(() => state.todos, saveTodos, { deep: true })

    return {
      ...toRefs(state),
      addTodo,
      deleteTodo,
      updateTodo,
      checkAll,
      clearAllCompletedTodos,
    }
  },
})
</script>
<style scoped>
.todo-container {
  width: 580px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
@/components/todoList/todo@/components/todoList/localStorageUtils